package view;

import java.awt.Color;
import java.awt.GridLayout;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

import model.Block;
import model.IModel;
import model.IModelObserver;
import model.LevelEntity;

/*
 * 
 * BlockPanel class
 * 
 * JPanel responsible for displaying and updating the visible game world.
 * 
 */

public class BlockPanel extends JPanel implements IModelObserver {

	private static final long serialVersionUID = -1112271234364641907L;
	JLabel[][] blockLabels = new JLabel[18][18];
	Map<Block, ImageIcon> blockSpriteMap = new HashMap<Block, ImageIcon>();
	private IModel model;

	/**
	 * BlockPanel
	 * 
	 * loads all of the blocks that are visable in a 900 by 900 grid
	 * 
	 * @param m
	 */
	public BlockPanel(IModel m) {
		this.model = m;
		this.setSize(900, 900);
		this.setLayout(new GridLayout(18, 18));
		this.setVisible(true);
		this.setLocation(-50, -150);
		this.setOpaque(false);
		importSprites();

		for (int i = 0; i < 18; i++) {
			for (int j = 0; j < 18; j++) {
				JLabel block = new JLabel();
				blockLabels[i][j] = block;
				this.add(block);
			}
		}
	}

	/**
	 * importSprite
	 * 
	 * imports sprites based upon the passed in string
	 * 
	 * @param path
	 * @return
	 */
	private ImageIcon importSprite(String path) {
		URL sprite = getClass().getResource(path);
		if (sprite == null) {
			return null;
		} else
			return new ImageIcon(sprite);
	}

	/**
	 * importSprites
	 * 
	 * imports all of the sprites for the different blocks
	 */
	private void importSprites() {
		ImageIcon dirt = importSprite("/textures/dirt.png");
		blockSpriteMap.put(Block.DIRT, dirt);

		ImageIcon grass = importSprite("/textures/dirtWithGrass.png");
		blockSpriteMap.put(Block.GRASS, grass);

		ImageIcon spike = importSprite("/textures/spike.png");
		blockSpriteMap.put(Block.SPIKE, spike);

		ImageIcon victory = importSprite("/textures/victory.png");
		blockSpriteMap.put(Block.VICTORY, victory);

		ImageIcon health = importSprite("/textures/healthPack.png");
		blockSpriteMap.put(Block.HEALTH, health);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see model.IModelObserver#modelChanged()
	 */
	@Override
	public void modelChanged() {
		LevelEntity currentBlock[][] = model.getBlocks();
		int offset = model.getWorldHead() % 50;

		for (int i = 0; i < 18; i++) {
			for (int j = 0; j < 11; j++) {
				if (currentBlock[i][j] != null) {
					;
					Block type = currentBlock[i][j].getType();
					JLabel label = blockLabels[14 - j][i];
					label.setIcon(blockSpriteMap.get(type));
					label.setBackground(Color.BLACK);
				} else {
					JLabel label = blockLabels[14 - j][i];
					label.setIcon(null);
				}
			}
		}
		setLocation((-50 - offset), -150);
		repaint();
	}
}
